package services

import (
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"my-go-gateway/dao"
	"my-go-gateway/dto"
	"my-go-gateway/middleware"
	"my-go-gateway/public"
	"time"
)

type AdminLoginService struct {
}

func (adminLoginService *AdminLoginService) AdminLogin(c *gin.Context, params *dto.AdminLoginInput) (*dto.AdminLoginOutput, error, middleware.ResponseCode) {

	tx, err := lib.GetGormPool("default")
	if err != nil {
		return nil, err, 2001
	}
	admin := &dao.Admin{}
	admin, err = admin.LoginCheck(c, tx, params)
	if err != nil {
		return nil, err, 2002
	}
	sessionInfo := &dto.AdminSessionInfo{
		ID:        admin.Id,
		UserName:  admin.UserName,
		LoginTime: time.Now(),
	}
	sessionBts, err := json.Marshal(sessionInfo)
	if err != nil {
		return nil, err, 2003
	}
	session := sessions.Default(c)
	session.Set(public.AdminSessionInfoKey, string(sessionBts))
	session.Save()
	out := &dto.AdminLoginOutput{Token: admin.UserName}
	return out, nil, 0
}
